<?php
## EMAIL #######################################################################
// Drop a record in the email_queue tbl
function email($recipient, $subject, $body, $header, $queue = FALSE) {
	$base =& Base::getInstance();

	if ($queue) {
		$table = $base->db->table['email_queue'];
		$field_value_array['recipient'] = $recipient;
		$field_value_array['subject'] = $subject;
		$field_value_array['header'] = $header;
		$field_value_array['body'] = $body;
		$field_value_array['datetime'] = date("Y-m-d H:i:s");

		$base->db->insert($table, $field_value_array);
		$base->db->query() or sql_error(__FILE__, __LINE__);
	}
	else {
		mail($recipient, $subject, $body, $header);
	}
}

## EMAIL QUEUE PARSE ###########################################################
// Send emails that are in the que waiting
function email_queue_parse($limit) {
	$base =& Base::getInstance();

	$table = $base->db->table['email_queue'];
	$fields_array[] = 'email_id';
	$fields_array[] = 'recipient';
	$fields_array[] = 'subject';
	$fields_array[] = 'header';
	$fields_array[] = 'body';

	$base->db->select($table, $fields_array);
	$base->db->order('id');
	$base->db->limit($limit);

	$base->db->query() or sql_error(__FILE__, __LINE__);

	// Put our result rows into an array ready to be returned to a foreach
	$emails = $base->db->result();

	foreach ($emails as $email) {
		email($email['recipient'], $email['subject'], $email['body'], $email['header']);
	}
}

## EMAIL QUEUE PURGE ###########################################################
// Remove sent email from queue
function email_queue_purge($id) {
	$base =& Base::getInstance();

	$table = $base->db->table['email_queue'];
	$base->db->delete($table);
	$base->db->where('email_id = '.$id);

	$base->db->query() or sql_error(__FILE__, __LINE__);
}
?>